<script>
import axios from "axios";
export default {
  name: "YiZhanComponent",
  data(){
    return{
      yizhanData:{
        pageNum:1,  //当前页
        pageSize:5,  //每页展示的条数
        courierStationName:"",//驿站名称
        communityName:"",//小区名称
        courierStationStatus:"",
        startTime:"",
        endTime:"",
      },
      total:1000,
      value1: "",
      list:[],
      addressAll: [],   //省市区
      address:[], //你选择的地址
      dialogFormVisible: false,
      communityNameTable:[],
      xiugai:false,
      imageUrl:"",
      modifyFormData:{
        addTime:"",
        courierStationAddress:"",
        courierStationCity:"",
        courierStationCommunityId:"",
        courierStationCommunityName:"",
        courierStationDistrict:"",
        courierStationId:"",
        courierStationImage:"",
        courierStationName:"",
        courierStationOrderCount:0,
        courierStationProvince:"",
        courierStationSort:1,
        courierStationStatus:1
      },

      addFormData:{
        courierStationAddress:"",  //驿站地址
        courierStationCity:"", //市
        courierStationCommunityId:"", //id
        courierStationDistrict:"", //县区
        courierStationImage:"", //图像
        courierStationName : "",
        courierStationProvince:"",
      },
      formLabelWidth: '120px',
      tableData2: [],
      /*头像上传*/
      fileList:[],
      headerObj: {
        authorization: localStorage.getItem('token')
      },
      img:'',
      noneBtnDealImg:false,
      uploadfileurl:"http://localhost:8080/files/upload",

      value: '',
      sta:1,
    }
  },
  created() {
    this.getAllProvinceAndCityList();
    //查询方法
    this.query();
    this.getCommunityNameList();
  },
  methods: {
    getCommunityNameList(){
      this.axios.get(
          "/getCommunityNameList").then((result)=>{
        console.log("获取小区列表数据.......")
        console.log(result.data)
        this.communityNameTable = result.data;
      }).catch(()=>{
        console.log("数据获取失败")
      })
    },
  handleClick(row) {
       console.log("上下架》。。。。。")
       console.log(row)
      if (row.courierStationStatus === 1) {
        this.sta = 0;
      } else {
        this.sta = 1;
      }
      this.axios.post("/modifyCourierServlet", {
        courierStationId: row.courierStationId,
        courierStationStatus: this.sta
      }).then(res => {
        this.query();
      }).catch(e => {
      })
    },

  addYiZhan(){
    this.resetData();
    this.dialogFormVisible = true;
  },

  xiugaiYiZhan(row){
    /*不同接口用的对话框的数据不一样  表单中的数据是与get请求对应一致*/
    this.xiugai = true;
    console.log(row)
    // this.modifyFormData = row;
    this.modifyFormData.courierStationId=row.courierStationId;
    this.modifyFormData.courierStationCommunityId=row.courierStationCommunityId;
    this.modifyFormData.courierStationName = row.courierStationName;
    this.modifyFormData.courierStationProvince=row.courierStationProvince;
    this.modifyFormData.courierStationDistrict=row.courierStationDistrict;
    this.modifyFormData.courierStationCity=row.courierStationCity;
    this.modifyFormData.courierStationAddress=row.courierStationAddress;
    this.modifyFormData.courierStationCommunityName=row.courierStationCommunityName;

  },

  confirmXiuGai(){
    /*courierStation/modifyCourierStation*/
    console.log("确认保存")
    this.xiugai = false;
    this.axios.post("/updateYiZhanServlet", {
      courierStationAddress:this.modifyFormData.courierStationAddress,
      courierStationCity:this.address[0],
      courierStationCommunityId:this.modifyFormData.courierStationId,
      courierStationCommunityName:this.modifyFormData.courierStationCommunityName,
      courierStationDistrict:this.address[2],
      courierStationId:this.modifyFormData.courierStationId,
      courierStationImage:this.modifyFormData.courierStationImage,
      courierStationName:this.modifyFormData.courierStationName,
      courierStationOrderCount:0,
      courierStationProvince:this.address[1],
      courierStationSort:1,
      courierStationStatus:1
    }).then((res)=>{
      console.log("修改的路径...")
      console.log(res)
      if(res.data.status===200){
        this.$message.success(res.data.message);
        this.query();
      }else {
        this.$message.error(res.data.message)
      }
    })
  },
  handleSizeChange(val) {
    /*console.log(`每页 ${val} 条`);*/
    this.yizhanData.pageSize=val;
    this.yizhanData.pageNum=1;

    this.query();
  },
  handleCurrentChange(val) {
    /*console.log(`当前页: ${val}`);*/
    this.yizhanData.pageNum=val;
    this.query();
  },

  // 搜索按钮
  onSubmit() {
    this.yizhanData.startTime=this.getDateString(this.value1[0]);
    this.yizhanData.endTime=this.getDateString(this.value1[1]);
    this.yizhanData.pageNum = 1;
    this.query();
  },
  //封装日期转为字符串的函数
  getDateString(date){
    if (!date) {
      return ""
    }
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },

  query(){
    this.axios.get(
        "/queryCourierServlet",{
          params:this.yizhanData
        }).then((result)=>{
      console.log(result.data)
      this.tableData2 = result.data.list;
      this.total = result.data.total;
    }).catch(()=>{
      console.log("数据获取失败")
    })

  },
  //获取省市
  getAllProvinceAndCityList() {
    // 获取全国所有省份和城市的列表
    var that = this;
    this.$http
        .get("https://restapi.amap.com/v3/config/district", {
          // 高德地图的API
          params: {
            key: "94214e26e4b0ec3a7d2ed9204f051583", // 这个是申请的 Key，读者自行写入
            keywords: "中国",
            subdistrict: 3,
            extensions: "base",
          },
        })
        .then((response) => {
          for(let i = 0;i<response.data.districts[0].districts.length;i++){
            let provinceMap = new Map();
            provinceMap.value = response.data.districts[0].districts[i].adcode;   //区域编号
            provinceMap.label = response.data.districts[0].districts[i].name;     //省名称
            provinceMap.children = [];
            that.addressAll.push(provinceMap);  //添加省份
            for(let j = 0;j < response.data.districts[0].districts[i].districts.length;j++){
              let cityMap = new Map()
              cityMap.value = response.data.districts[0].districts[i].districts[j].adcode;   //区域编号
              cityMap.label = response.data.districts[0].districts[i].districts[j].name;     //市名称
              cityMap.children = [];
              provinceMap.children.push(cityMap); //添加市
              for(let k = 0;k <response.data.districts[0].districts[i].districts[j].districts.length;k++){
                let areaMap = new Map()
                areaMap.value = response.data.districts[0].districts[i].districts[j].districts[k].adcode;   //区域编号
                areaMap.label = response.data.districts[0].districts[i].districts[j].districts[k].name;     //区县名称
                cityMap.children.push(areaMap);   //添加区县
              }
            }
          }
        });
  },

  // 重置数据
  resetData(){
    this.addFormData={
      courierStationAddress:"",  //驿站地址
      courierStationCity:"", //市
      courierStationCommunityId:"", //id
      courierStationDistrict:"", //县区
      courierStationImage:"", //图像
      courierStationName : "",
      courierStationProvince:"",
    };
    this.imageUrl = "";
  },
  add(){
    this.dialogFormVisible = false;
    this.axios.post("/addYiZhanServlet", {
      courierStationAddress:this.addFormData.courierStationAddress,  //驿站地址
      courierStationCity:this.address[1], //市
      courierStationDistrict:this.address[2], //县区
      courierStationImage:"", //图像
      courierStationName : this.addFormData.courierStationName,
      courierStationProvince:this.address[0],
    }).then((res)=>{
      console.log(res.data)
      if(res.data.status===200){
        this.$message.success(res.data.message);
        this.query();
      }else {
        this.$message.error(res.data.message)
      }
    })
  },


    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg';
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    }
  }

}
</script>

<template>
  <div class="yizhan">
    <el-form :inline="true" :model="yizhanData" class="demo-form-inline">
      <el-form-item>
        <span class="mingzi">驿站名称:</span>
        <el-input v-model="yizhanData.courierStationName" style="width: 200px;" clearable placeholder="请输入驿站名称"></el-input>
      </el-form-item>
      <el-form-item>
        <span class="mingzi">小区名称:</span>
        <el-input v-model="yizhanData.communityName" style="width: 200px;" clearable placeholder="请输入小区名称"></el-input>
      </el-form-item>
      <el-form-item>
        <span class="mingzi">添加时间:</span>
        <el-date-picker
            v-model="value1"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 320px;"
            clearable>
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">搜索</el-button>
      </el-form-item>
    </el-form>


    <div style="margin-top: 8px">
      <!--      添加驿站的按钮-->
      <el-button type="text" @click="addYiZhan" class="addMenDian">添加驿站</el-button>

      <!--    点击编辑按钮弹出的对话框-->
      <el-dialog title="编辑驿站" :visible.sync="xiugai">
        <el-form :model="modifyFormData">
          <el-form-item label="驿站名字" :label-width="formLabelWidth">
            <el-input v-model="modifyFormData.courierStationName" autocomplete="off" placeholder="请输入驿站名字"></el-input>
          </el-form-item>

          <el-form-item label="驿站图片" :label-width="formLabelWidth">
            <el-upload
                :limit="1"

                class="avatar-uploader"
                :class="noneBtnDealImg ? 'disUoloadSty':''"
                :action="uploadfileurl"
                :file-list="fileList"
                :headers="headerObj"
                style="padding:30px 0 ;"
                list-type="picture-card"
                :on-success="(res, file, fileList)=>handleAvatarSuccess(res, file, fileList,'img')"
                name="image"
                :on-remove="(file,fileList)=>handleRemove(file,fileList,'img')">
              <i class="el-icon-plus" ></i>
            </el-upload>
            <el-button type="primary">提 交</el-button>
          </el-form-item>


          <el-form-item label="所属地区" :label-width="formLabelWidth">
            <el-cascader
                :options="addressAll"
                clearable
                v-model="address"
                :props="{value:'label'}"
            ></el-cascader>
          </el-form-item>
          <el-form-item :label-width="formLabelWidth">
            <!--          看绑定的值-->
            <el-input v-model="modifyFormData.courierStationAddress" autocomplete="on" placeholder="请填写详细地址"></el-input>
          </el-form-item>

          <el-form-item label="所属小区" :label-width="formLabelWidth">
            <el-select v-model="modifyFormData.courierStationCommunityName" filterable placeholder="请选择">
              <el-option
                  v-for="(value,index) in communityNameTable"
                  :key="index"
                  :label="value.community_name"
                  :value="value.community_id">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="confirmXiuGai">确认保存</el-button>
        </div>
      </el-dialog>
    </div>

    <!--    点击添加驿站按钮弹出的对话框-->
    <el-dialog title="添加驿站" :visible.sync="dialogFormVisible">
      <el-form :model="addFormData">
        <el-form-item label="驿站名字" :label-width="formLabelWidth">
          <el-input v-model="addFormData.courierStationName" autocomplete="off" placeholder="请输入驿站名字"></el-input>
        </el-form-item>
        <el-form-item label="驿站图片" :label-width="formLabelWidth">

          <el-upload
              class="avatar-uploader"
              action="http://localhost:8080/panghudaojiaBackend/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>


        <el-form-item label="所属地区" :label-width="formLabelWidth">
          <el-cascader
              :options="addressAll"
              clearable
              v-model="address"
              :props="{value:'label'}"
          ></el-cascader>
        </el-form-item>
        <el-form-item :label-width="formLabelWidth">
          <!--          看绑定的值-->
          <el-input v-model="addFormData.courierStationAddress" autocomplete="on" placeholder="请填写详细地址"></el-input>
        </el-form-item>

        <el-form-item label="所属小区" :label-width="formLabelWidth">
          <el-select v-model="modifyFormData.courierStationCommunityName" filterable placeholder="请选择">
            <el-option
                v-for="(value,index) in communityNameTable"
                :key="index"
                :label="value.community_name"
                :value="value.community_id">
            </el-option>
          </el-select>
        </el-form-item>



      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="add">确认保存</el-button>
      </div>
    </el-dialog>

    <!--  表格区域-->
    <el-table
        :data="tableData2"
        :cell-style="{'text-align':'center'}"
        :header-cell-style="{background: '#1890ff',color: '#ffffff','text-align': 'center'}"
        border
        style="width: 100%">
      <el-table-column
          prop="courierStationId"
          label="ID">
      </el-table-column>
      <el-table-column
          prop="courierStationName"
          label="驿站名字">
      </el-table-column>
      <el-table-column
          prop="courierStationImage"
          label="驿站照片">
      </el-table-column>
      <el-table-column
          prop="courierStationProvince,courierStationCity,courierStationDistrict,courierStationAddress"
          label="驿站地址">
        <template slot-scope="scope">
          {{scope.row.courierStationProvince}}{{scope.row.courierStationCity}}{{scope.row.courierStationDistrict}}{{scope.row.courierStationAddress}}
        </template>


      </el-table-column>
      <el-table-column
          prop="courierStationCommunityName"
          label="所在小区"
      >
      </el-table-column>
      <el-table-column
          prop="courierStationOrderCount"
          label="订单总数">
      </el-table-column>
      <el-table-column
          prop="addTime"
          label="添加时间">
      </el-table-column>

      <el-table-column
          prop="courierStationStatus"
          label="状态">
        <template slot-scope="scope1">
          <el-button  class="btn1" v-if="scope1.row.courierStationStatus===1">上架</el-button>
          <el-button   class="btn2" v-else>下架</el-button>
        </template>
      </el-table-column>
      <el-table-column
          label="操作"
         >
        <!--       插槽传值，值都在scope中 -->
        <template slot-scope="scope2">
          <el-button @click="handleClick(scope2.row)" type="text" size="small" v-if="scope2.row.courierStationStatus===1">立即下架</el-button>

          <el-button @click="handleClick(scope2.row)" type="text" size="small" v-else>立即上架</el-button>

          <el-button type="text" size="small" @click="xiugaiYiZhan(scope2.row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>


    <!-- 分页 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="yizhanData.pageNum"
        :page-sizes="[3,5,7,10]"
        :page-size="yizhanData.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
  </div>
</template>

<style scoped>
.yizhan{
  height: 800px;
}
.btn1{
  background-color: #e7faf0;
  border-color: #d0f5e0;
  color: #13ce66;
}

.btn2{
  color: #F56C6C;
  background: #fef0f0;
  border-color: #fbc4c4;
  cursor: default;
}
.el-form-item{
  margin-right: 20px;
}
.mingzi{
  font-weight: 500;
  font-size: 16px;
  margin-right: 15px;
}

.addMenDian{
  padding: 10px 20px;
  color: #FFF;
  background-color: #409EFF;
  border-color: #409EFF;
  margin-bottom: 20px;
}


.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>